//
//  RXOauthController.swift
//  weibo
//
//  Created by uncle-R on 15/12/18.
//  Copyright © 2015年 uncle-R. All rights reserved.
//
import UIKit
import SVProgressHUD

class RXOauthController: UIViewController ,UIWebViewDelegate{
    
    
    private var weBView: UIWebView = {
        
        let weBview = UIWebView()
        
        return weBview
    }()
    //不需要约束
    override func loadView() {
        
        super.loadView()
        
        self.view = weBView
        
        weBView.delegate = self
    
    }
    //MARK: - 实现webView的代理方法 ---------目的 在加载页面的时候进行判断.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!.absoluteString

//        不是授权地址的话  直接加载就可以
        if !url.hasPrefix(RXNetworkTool.sharedInsatance.redirect_uri) {
            return true
        }
        
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权:会以code=开头 http://www.baidu.com/?code=a61c2d7ec7b8c4c9c1962bf4354354c5
        
//        当授权同意. 访问地址中会带一个code参数,截取
        //query  是?后面的内容.
        if let query = request.URL?.query{
            //能到这里来 说明query有值
            let codeStr = "code="
            //判断是否以code开头
            if query.hasPrefix(codeStr){
                //截取code的值
                let quNS = query as NSString
                let code = quNS.substringFromIndex(codeStr.characters.count)
                //获取code然后进行请求
                loadACcessToken(code)
                
            }
            else{
                cancle()
            }
            
        }
        else{
            print("query没有值")
        }
        
        
        return false
        
    }
    
   //架子AccessToken
    func loadACcessToken(code:String){
        RXNetworkTool.sharedInsatance.loadAccessToken(code) { (result, error) -> () in
            //从单例中加载完之后从闭包中取值
            
            //print("result:\(result) error:\(error)")
            if error != nil && result == nil{
                print("error:\(error)")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                //延迟1秒关闭
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    // 关闭授权控制器
                    self.cancle()
                })
            }
                //保存AccessToken
                let userAccount = RXUserAccount(dict: result!)
            
                //print("result:-----\(result)--------------")
                
                //保存到沙河
                userAccount.saveUserAccount()
                
                print("用户信息已保存到沙盒中")
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(true)
   
            
        }
        
        
        
    }
    
    
    
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fullPwd")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        navigationItem.title = "登录"
        
        let URL = RXNetworkTool.sharedInsatance.OauthURL()
        let requset = NSURLRequest(URL: URL)
        //加载请求  ->目的获取
        weBView.loadRequest(requset)

    }
    
    ///充满屏幕.
    func fullPwd(){
let js = "document.getElementById('userId').value='18046729942'; document.getElementById('passwd').value='a5419459';"
        
        // 让webView来执行js代码
        weBView.stringByEvaluatingJavaScriptFromString(js)

    }
//MARK: - 关闭授权界面
    func cancle(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
////MARK: - 处理网络请求的提示
    
    func webViewDidStartLoad(webView: UIWebView) {
        
          SVProgressHUD.showWithStatus("正在拼命加载中", maskType: SVProgressHUDMaskType.Black)
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
        
    }
    
    
    
    
    
    
    
    
    
    
   
}
